package com.thinkit.bigdata.web.service.impl.sec;

import com.thinkit.bigdata.web.dao.config.SysResourceMapper;
import com.thinkit.bigdata.web.dao.sec.PermissionMapper;
import com.thinkit.bigdata.web.model.config.SysResource;
import com.thinkit.bigdata.web.model.config.SysResourceExample;
import com.thinkit.bigdata.web.model.sec.JsTreeNode;
import com.thinkit.bigdata.web.service.sec.PermissionService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by lihongli on 2018/9/7
 */
@Service
public class PermissionServiceImpl implements PermissionService {

    @Resource
    private PermissionMapper mapper;

    @Resource
    private SysResourceMapper resourceMapper;

    @Override
    public List<SysResource> selectPermissions(Long roleId) {
        return mapper.selectPermissions(roleId);
    }

    @Override
    public Integer insertPermissions(Long roleId, List<Long> idList) {
        // 先删除原有的权限信息
        int rowNum = mapper.deletePermissions(roleId);
        if (idList == null || idList.isEmpty()) {
            return rowNum;
        }
        // 全选的时候 移除根节点对应的-1
        if(idList.contains(-1)){
            idList.remove(new Integer(-1));
        }
        // 重新插入所有的权限信息
        return mapper.insertPermissions(roleId, idList);
    }

    @Override
    public JsTreeNode selectResources(JsTreeNode tree) {
        // 先查询父级资源为空的资源信息
        SysResourceExample example = new SysResourceExample();
        // 只查询出已启用的菜单信息
        example.createCriteria().andParentidIsNull().andStatusEqualTo(1);
        List<SysResource> resourceList = resourceMapper.selectByExample(example);
        for (SysResource resource : resourceList) {
            JsTreeNode tmp = new JsTreeNode();
            tmp.setId(resource.getId());
            tmp.setText(resource.getName());
            resoureRecursion(resource.getId(), tmp);
            tree.getChildren().add(tmp);
        }
        return tree;
    }

    // 递归获取树形数据
    private void resoureRecursion(Long resourceId, JsTreeNode treeNode) {
        // 获取resourceId下所有资源信息
        SysResourceExample resourceExample = new SysResourceExample();
        // 只查询出已启用的菜单信息
        resourceExample.createCriteria().andParentidEqualTo(resourceId).andStatusEqualTo(1);
        List<SysResource> resources = resourceMapper.selectByExample(resourceExample);
        List<JsTreeNode> children = new ArrayList<>();
        for (SysResource resource : resources) {
            JsTreeNode tmp = new JsTreeNode();
            tmp.setId(resource.getId());
            tmp.setText(resource.getName());
            resoureRecursion(resource.getId(), tmp);
            children.add(tmp);
        }
        treeNode.setChildren(children);
    }

    @Override
    public List<SysResource> selectIndexMenu(List<Long> roleIdList) {
        return mapper.selectIndexMenu(roleIdList);
    }
}
